/*
 * Copyright (c) 2001-2003 Swedish Institute of Computer Science.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 * This file is part of the lwIP TCP/IP stack.
 *
 * Author: Adam Dunkels <adam@sics.se>
 *
 */

#include  <ucos_ii.h>
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "arch/sys_arch.h"


static lwip_mbox_t* lwip_mbox_free_list;
static lwip_mbox_t lwip_mbox[LWIP_MBOX_SIZE];

/*****************************************************************************
Function      : sys_init
Description   :
Input         :
Output        :
Return        :
Others        :
*****************************************************************************/
void sys_init(void)
{
    int i;

    lwip_mbox_free_list = (lwip_mbox_t *)0;
    for (i = 0; i < LWIP_MBOX_SIZE; i++) {
        lwip_mbox[i].next = lwip_mbox_free_list;
        lwip_mbox_free_list = &lwip_mbox[i];
    }
}

/*****************************************************************************
Function      : sys_ms_to_ticks
Description   :
Input         : @param time_ms time in milliseconds
Output        :
Return        : time in OS clock ticks
Others        :
*****************************************************************************/
u32_t sys_ms_to_ticks(u32_t time_ms)
{
    u32_t time_ticks;

    if (time_ms) {
        time_ticks = (time_ms * OS_TICKS_PER_SEC)/1000;
        if (time_ticks < 1) {
            time_ticks = 1;
        }
    } else {
        time_ticks = 0;
    }

    return time_ticks;
}

/*****************************************************************************
Function      : sys_ticks_to_ms
Description   :
Input         : @param time_ticks time in OS clock ticks
Output        :
Return        : time in milliseconds
Others        :
*****************************************************************************/
u32_t sys_ticks_to_ms(u32_t time_ticks)
{
    u32_t time_ms;

    time_ms = (time_ticks*1000)/OS_TICKS_PER_SEC;

    return time_ms;
}

/*****************************************************************************
Function      : sys_sem_new
Description   : Create a new semaphore
Input         : @param sem pointer to the semaphore to create
                @param count initial count of the semaphore
Output        :
Return        : ERR_OK if successful, another err_t otherwise
Others        :
*****************************************************************************/
err_t sys_sem_new(sys_sem_t *sem, u8_t count)
{
    *sem = OSSemCreate(count);
    if (*sem == (sys_sem_t)0) {
        return ERR_MEM;
    }
    return ERR_OK;
}

/*****************************************************************************
Function      : sys_sem_signal
Description   : Signals a semaphore
Input         : @param sem the semaphore to signal

Output        :
Return        :
Others        :
*****************************************************************************/
void sys_sem_signal(sys_sem_t *sem)
{
    OSSemPost(*sem);
}

/*****************************************************************************
Function      : sys_arch_sem_wait
Description   : Wait for a semaphore for the specified timeout
Input         : @param sem the semaphore to wait for
                @param timeout timeout in milliseconds to wait (0 = wait forever)
Output        :
Return        : time (in milliseconds) waited for the semaphore
                or SYS_ARCH_TIMEOUT on timeout
Others        :
*****************************************************************************/
u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout)
{
    INT8U err;
    INT32U start_ticks, end_ticks;

    start_ticks = OSTimeGet();
    OSSemPend(*sem, sys_ms_to_ticks(timeout), &err);
    end_ticks = OSTimeGet();

    if (err == OS_ERR_NONE) {
        return sys_ticks_to_ms((u32_t)(end_ticks-start_ticks));
    }
    return SYS_ARCH_TIMEOUT;
}

/*****************************************************************************
Function      : sys_sem_free
Description   : Delete a semaphore
Input         : @param sem semaphore to delete

Output        :
Return        :
Others        :
*****************************************************************************/
void sys_sem_free(sys_sem_t *sem)
{
    INT8U err;

    if (*sem) {
        while (OSSemDel(*sem, OS_DEL_NO_PEND, &err) != (OS_EVENT *)0) {
            OSTimeDlyHMSM(0, 0, 0, 100);
        }
    }
}

/*****************************************************************************
Function      : sys_sem_valid
Description   : Check if a sempahore is valid/allocated
Input         :

Output        :
Return        : 1 for valid, 0 for invalid
Others        :
*****************************************************************************/
int sys_sem_valid(sys_sem_t *sem)
{
    return ((*sem == SYS_SEM_NULL)? 0 : 1);
}

/*****************************************************************************
Function      : sys_sem_set_invalid
Description   : Set a semaphore invalid so that sys_sem_valid returns 0
Input         :

Output        :
Return        : 1 for valid, 0 for invalid
Others        :
*****************************************************************************/
void sys_sem_set_invalid(sys_sem_t *sem)
{
    SYS_ARCH_DECL_PROTECT(lev);

    SYS_ARCH_PROTECT(lev);
    *sem = SYS_SEM_NULL;
    SYS_ARCH_UNPROTECT(lev);
}

/*****************************************************************************
Function      : sys_mbox_new
Description   : Create a new mbox of specified size
Input         : @param mbox pointer to the mbox to create
                @param size (miminum) number of messages in this mbox
Output        :
Return        : return ERR_OK if successful, another err_t otherwise
Others        :
*****************************************************************************/
err_t sys_mbox_new(sys_mbox_t *mbox, int size)
{
    SYS_ARCH_DECL_PROTECT(lev);
    lwip_mbox_t *lwip_mbox;

    SYS_ARCH_PROTECT(lev);
    lwip_mbox = lwip_mbox_free_list;
    if (lwip_mbox_free_list != (lwip_mbox_t *)0) {
        lwip_mbox_free_list = lwip_mbox_free_list->next;
    }
    SYS_ARCH_UNPROTECT(lev);

    if (lwip_mbox != (lwip_mbox_t *)0) {
        lwip_mbox->mbox = OSQCreate(lwip_mbox->msg, LWIP_MBOX_MSG_SIZE);
        if (lwip_mbox->mbox != (OS_EVENT *)0) {
            *mbox = lwip_mbox;
            return ERR_OK;
        }
        SYS_ARCH_PROTECT(lev);
        lwip_mbox->next = lwip_mbox_free_list;
        lwip_mbox_free_list = lwip_mbox;
        SYS_ARCH_UNPROTECT(lev);
    }

    *mbox = (sys_mbox_t)0;

    return ERR_MEM;
}

/*****************************************************************************
Function      : sys_mbox_post
Description   : Post a message to an mbox - may not fail
                -> blocks if full, only used from tasks not from ISR
Input         : @param mbox mbox to posts the message
                @param msg message to post (ATTENTION: can be NULL)
Output        :
Return        :
Others        :
*****************************************************************************/
void sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
    while (OSQPost((*mbox)->mbox, msg) == OS_ERR_Q_FULL) {
        OSTimeDlyHMSM(0, 0, 0, 100);
    }
}

/*****************************************************************************
Function      : sys_mbox_trypost
Description   : Try to post a message to an mbox - may fail if full or ISR
Input         : @param mbox mbox to posts the message
                @param msg message to post (ATTENTION: can be NULL)
Output        :
Return        : return ERR_OK if successful, another err_t otherwise
Others        :
*****************************************************************************/
err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
    if(OSQPost((*mbox)->mbox, msg) == OS_ERR_NONE) {
        return ERR_OK;
    }
    return ERR_MEM;
}

/*****************************************************************************
Function      : sys_arch_mbox_fetch
Description   : Wait for a new message to arrive in the mbox
Input         : @param mbox mbox to get a message from
                @param msg pointer where the message is stored
                @param timeout maximum time (in milliseconds) to wait for a message
Output        :
Return        : time (in milliseconds) waited for a message, may be 0 if not waited
                or SYS_ARCH_TIMEOUT on timeout
                The returned time has to be accurate to prevent timer jitter!
Others        :
*****************************************************************************/
u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout)
{
    INT8U err;
    INT32U start_ticks, end_ticks;

    start_ticks = OSTimeGet();
    *msg = OSQPend((*mbox)->mbox, sys_ms_to_ticks(timeout), &err);
    end_ticks = OSTimeGet();

    if (err == OS_ERR_NONE) {
        return sys_ticks_to_ms((u32_t)(end_ticks-start_ticks));
    }
    return SYS_ARCH_TIMEOUT;
}

/*****************************************************************************
Function      : sys_arch_mbox_tryfetch
Description   : Wait for a new message to arrive in the mbox
Input         : @param mbox mbox to get a message from
                @param msg pointer where the message is stored
                @param timeout maximum time (in milliseconds) to wait for a message
Output        :
Return        : 0 (milliseconds) if a message has been received
                or SYS_MBOX_EMPTY if the mailbox is empty
Others        :
*****************************************************************************/
u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
    INT8U err;

    *msg = OSQAccept ((*mbox)->mbox, &err);
    if (err == OS_ERR_NONE) {
        return 0;
    }
    return SYS_MBOX_EMPTY;
}

/*****************************************************************************
Function      : sys_mbox_free
Description   : Delete an mbox
Input         : @param mbox mbox to delete
Output        :
Return        :
Others        :
*****************************************************************************/
void sys_mbox_free(sys_mbox_t *mbox)
{
    SYS_ARCH_DECL_PROTECT(lev);
    INT8U err;

    if (*mbox) {
        while (OSQDel((*mbox)->mbox, OS_DEL_NO_PEND, &err) != (OS_EVENT *)0) {
            OSTimeDlyHMSM(0, 0, 0, 100);
        }
        SYS_ARCH_PROTECT(lev);
        (*mbox)->next = lwip_mbox_free_list;
        lwip_mbox_free_list = *mbox;
        SYS_ARCH_UNPROTECT(lev);
    }
}

/*****************************************************************************
Function      : sys_mbox_valid
Description   : Check if an mbox is valid/allocated
Input         :
Output        :
Return        : return 1 for valid, 0 for invalid
Others        :
*****************************************************************************/
int sys_mbox_valid(sys_mbox_t *mbox)
{
    return ((*mbox == SYS_MBOX_NULL)? 0 : 1);
}

/*****************************************************************************
Function      : sys_mbox_valid
Description   : Set an mbox invalid so that sys_mbox_valid returns 0
Input         :
Output        :
Return        :
Others        :
*****************************************************************************/
void sys_mbox_set_invalid(sys_mbox_t *mbox)
{
    SYS_ARCH_DECL_PROTECT(lev);

    SYS_ARCH_PROTECT(lev);
    *mbox = SYS_MBOX_NULL;
    SYS_ARCH_UNPROTECT(lev);
}

/*****************************************************************************
Function      : sys_thread_new
Description   : Creates a new thread
Input         : @param name human-readable name for the thread (used for debugging purposes)
                @param thread thread-function
                @param arg parameter passed to 'thread'
                @param stacksize stack size in bytes for the new thread (may be ignored by ports)
                @param prio priority of the new thread (may be ignored by ports)
Output        :
Return        :
Others        :
*****************************************************************************/
sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio)
{
    OS_STK *stack;
    INT8U err;

    (void)name;

    stack = (OS_STK *)mem_malloc((mem_size_t)(stacksize*sizeof(OS_STK)));
    if (stack == (OS_STK *)0) {
        /*memory error*/
        while(1);
    }

    err = OSTaskCreate(thread, arg, &stack[stacksize-1], prio);
    if (err != OS_ERR_NONE) {
        /*task create fail*/
        while(1);
    }

    return prio;
}

/*****************************************************************************
Function      : sys_time_delay
Description   :
Input         : time (in milliseconds) to delay
Output        :
Return        :
Others        :
*****************************************************************************/
void sys_time_delay(u32_t time_ms)
{
    OSTimeDlyHMSM(0, 0, 0, time_ms);
}


/*****************************************************************************
Function      : sys_jiffies
Description   : Ticks/jiffies since power up
Input         :
Output        :
Return        :
Others        :
*****************************************************************************/
u32_t sys_jiffies(void)
{
    return OSTimeGet();
}

/*****************************************************************************
Function      : sys_now
Description   :
Input         :
Output        :
Return        : Returns the current time in milliseconds,
                may be the same as sys_jiffies or at least based on it.
Others        :
*****************************************************************************/
u32_t sys_now(void)
{
    INT32U ticks;

    ticks = OSTimeGet();
    return sys_ticks_to_ms(ticks);
}

